import { useEffect } from "react";
import { useDictionaryStore } from "@/store/useDictionaryStore";
import dictService from "@/api/services/system/dictService";

const useDictionaryBatch = (codes: string[]) => {
  const { dictionaries, setDictionary, loading } = useDictionaryStore();

  useEffect(() => {
    const fetchMissingDictionaries = async () => {
      const missingCodes = codes.filter(code => !dictionaries[code]);

      if (missingCodes.length === 0 || loading) return;

      await Promise.all(
        missingCodes.map(async (code) => {
          try {
            const data = await dictService.getItemByCode(code);
            const formattedData = data.map((item: { itemText: string; itemValue: string; color: string }) => ({
              label: item.itemText,
              value: item.itemValue,
              color: item.color,
            }));
            setDictionary(code, formattedData);
          } catch (err) {
            console.error(`加载字典 ${code} 失败`, err);
          }
        })
      );
    };

    fetchMissingDictionaries();
  }, [JSON.stringify(codes), dictionaries, loading, setDictionary]);

  const result: Record<string, any[]> = {};
  codes.forEach(code => {
    result[code] = dictionaries[code] || [];
  });

  return result;
};

export default useDictionaryBatch;
